import React, { useState, useEffect } from 'react';
import { Button, Icon, message } from 'antd';
import COMMONATION from 'service/apis/commonAction';
import { connect } from 'dva';
import './index.styl';


function UploadPicIE({ dispatch, commonAction: { uploadInfo }, getImgSrc, editImg, index = 0 }) {
  const [imgSrc, setImgSrc] = useState('')
  useEffect(() => {
    dispatch({
      type: 'commonAction/getToken',
    });
  }, [dispatch]);

  useEffect(() => {
    setImgSrc(editImg);
  }, [editImg]);

  function submitFile(e) {
    let _number = 0;
    const img_type = ['jpg', 'jpeg', 'png']
    const ori_file_name = e.target.value.split("\\")[e.target.value.split("\\").length - 1]
    if (!(img_type.includes(ori_file_name.split('.')[ori_file_name.split('.').length - 1].toLowerCase()))) {
      message.error(`上传图片格式不正确，请重新上传`);
      return
    }
    const form = document.forms[index]
    form.submit()
    const targetIframe = document.getElementById('targetIframe')
    targetIframe.addEventListener('load', function () {
      const preArray = document.getElementById('targetIframe').contentDocument.getElementsByTagName('pre');
      const data = preArray[0].innerText
      const code = data.split('code=')[1].split(',')[0]
      if (code === '000000') {
        if (_number === 0) {
          _number++;
          message.success(`上传成功`);
        }
        const dataObj = JSON.parse(data.split('data=')[1].split(')')[0])
        setImgSrc(dataObj.url);
        getImgSrc(dataObj.url);
      } else {
        message.error(`图片上传失败`);
      }
    })
  }

  function openFile() {
    const InputFile = document.getElementById('file')
    InputFile.click()
  }

  return (
    <div className="uploadPicIE">
      <div className="flexWrapper">
        <div>
          <Button className="btn fix-btn" onClick={openFile}>
            <Icon type="upload"/> 上传
          </Button>
          <form
            action={COMMONATION.UPLOAD_IMG_IE9}
            method="post"
            enctype="multipart/form-data"
            hidden="hidden"
            target="targetIframe"
          >
            <input type="file" onChange={submitFile} name="file" id="file" accept="image/jpg,image/jpeg,image/png"/>
            <input type="hidden" name="Authorization" value={'Bearer ' + uploadInfo.token}/>
          </form>
          <iframe name="targetIframe" id="targetIframe" style={{display: 'none'}}></iframe>
        </div>
        <div className="tip">
          请上传一张设主图，建议比例为16/9;支持格式：jpg、jpeg、png，不超过10M。
        </div>
      </div>
      <div style={{width:'160px', height: '90px', marginLeft: '150px'}} onClick={openFile}>
        {imgSrc ? <img src={imgSrc} alt="avatar" style={{ width: '100%',height: '100%' }} /> : ''}
      </div>
    </div>
  );
}

export default connect(({ commonAction }) => ({
  commonAction,
}))(UploadPicIE);


